<?php

class User extends Module
{
	function __construct ($db){
		$this->set_db($db);
	}

	function get_user_level(){

	}

	function authen($username, $password){

		if($username == ""){
			$_SESSION['error'] = "กุณากรอก ชื่อล็อกอิน";
			return false;
		}

		if($password == ""){
			$_SESSION['error'] = "กุณากรอก รหัสผ่าน";
			return false;
		}

		$sql = "SELECT * FROM user WHERE username = '".$username."' and active = 1";
		$user = $this->db->queryUniqueObject($sql);

		if($user->password == $password){
			$_SESSION['login'] = true;
			$_SESSION['uid'] = $user->uid;
			$_SESSION['user_group'] = $user->user_group;
			$_SESSION['username'] = $user->username;
			$_SESSION['name'] = $user->name;
			$_SESSION['email'] = $user->email;
			$_SESSION['avatar'] = $user->avatar;

			$_SESSION['error'] = '';
			return true;

		}else{
			$_SESSION['login'] = false;
			$_SESSION['error'] = "ชื่อล็อกอิน หรือ รหัสผ่าน ไม่ถูกต้อง";
			return false;
		}

		return false;
	}

	function get_level_name($level){
		switch($level){
			case 1 : return "admin";
			case 2 : return "board";
			case 3 : return "officer";
			case 4 : return "assessor";
		}
	}

	function get_level($level_name){
		switch($level_name){
			case "admin" : return 1;
			case "board" : return 2;
			case "officer" : return 3;
			case "assessor" : return 4;
		}
	}

	function if_user_exsits($username){

		$sql = "SELECT * FROM user WHERE username = '$username'";

		if($this->db->queryUniqueValue($sql)){
			return true;
		}

		return false;
	}

	function get_user_by_email($email){

		$sql = "SELECT * FROM user WHERE email = '$email'";
		$line = $this->db->queryUniqueObject($sql);

		foreach($line as $k => $v){
			$result[$k] = $v;
		}

		return $result;
	}

	function if_email_exsits($email){

		$sql = "SELECT uid FROM user WHERE email = '$email'";

		if($this->db->queryUniqueValue($sql)){
			return true;
		}

		return false;
	}

    function register($req){

		$id = $this->db->insert("user", $req);

		return $id;
    }

	function compare($f1, $f2){
		if($f1 === $f2){
			return true;
		}
		return false;
	}

	function check($req){
		
		if($req['username'] == ""){
			alert("please enter username");
			return false;
		}

		if($req['password'] == ""){
			alert("please enter password");
			return false;
		}

		if($req['email'] == ""){
			alert("please enter email");
			return false;
		}

		return true;
	}

	function get_name(){
		return $this->name;
	}
}

?>